package request

import (
	"encoding/json"

	"qmp_go_push/models"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"qmp_go_push/middleware"
)

const (
	ContentTypeJson       = "application/json"
	ContentTypeForm       = "multipart/form-data"
	ContentTypeUrlencoded = "application/x-www-form-urlencoded"
)

type Request struct {
	GinContext *gin.Context
	DBContext  *models.DBContext

	validate binding.StructValidator
	body     []byte
}

func (req *Request) ShouldBind(obj any) error {
	switch b := binding.Default(req.GinContext.Request.Method, req.GinContext.ContentType()); b {
	case binding.Form, binding.FormMultipart:
		return req.GinContext.ShouldBindWith(obj, b)
	default:
		err := json.Unmarshal(req.body, obj)
		if err != nil {
			return err
		}
		req.validate = DefaultStructValidator()
		return req.validate.ValidateStruct(obj)
	}
}

func (req *Request) SetBody() {
	if body, ok := req.GinContext.Get(middleware.RequestParamKey); ok {
		req.body = body.([]byte)
	}
}

func (req *Request) GetBody() string {
	return string(req.body)
}
